<template>
  <div class="guide-edit-page">
    <div class="page-header mb-6">
      <div class="flex items-center justify-between">
        <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
          {{ isEdit ? "编辑导游" : "添加导游" }}
        </h2>
        <el-button @click="goBack">
          <el-icon class="mr-1"><Back /></el-icon>返回
        </el-button>
      </div>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="max-w-4xl"
      v-loading="loading"
    >
      <!-- 基本信息 -->
      <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm mb-6">
        <h3
          class="text-lg font-bold text-gray-900 dark:text-white mb-4 border-b border-gray-100 dark:border-gray-700 pb-2"
        >
          基本信息
        </h3>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <el-form-item label="导游姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入导游姓名" />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              placeholder="选择出生日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="!w-full"
            />
          </el-form-item>

          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
          </el-form-item>

          <el-form-item label="所在地区" prop="location">
            <el-cascader
              v-model="form.location"
              :options="regionOptions"
              placeholder="请选择所在地区"
              class="!w-full"
            />
          </el-form-item>

          <el-form-item label="从业年限" prop="experience">
            <el-input-number
              v-model="form.experience"
              :min="0"
              :max="50"
              class="!w-full"
            />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="form.status"
              placeholder="请选择状态"
              class="!w-full"
            >
              <el-option label="已认证" value="verified" />
              <el-option label="未认证" value="unverified" />
              <el-option label="审核中" value="pending" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-form-item>
        </div>

        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadAvatar"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar-image" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="text-xs text-gray-500 mt-1">
            建议上传正方形图片，大小不超过2MB
          </div>
        </el-form-item>
      </div>

      <!-- 专业信息 -->
      <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm mb-6">
        <h3
          class="text-lg font-bold text-gray-900 dark:text-white mb-4 border-b border-gray-100 dark:border-gray-700 pb-2"
        >
          专业信息
        </h3>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <el-form-item label="导游证号" prop="certificateNumber">
            <el-input
              v-model="form.certificateNumber"
              placeholder="请输入导游证号"
            />
          </el-form-item>

          <el-form-item label="发证机构" prop="issuingAuthority">
            <el-input
              v-model="form.issuingAuthority"
              placeholder="请输入发证机构"
            />
          </el-form-item>

          <el-form-item label="证书类型" prop="certificateType">
            <el-select
              v-model="form.certificateType"
              placeholder="请选择证书类型"
              class="!w-full"
            >
              <el-option label="导游资格证" value="导游资格证" />
              <el-option label="导游等级证" value="导游等级证" />
              <el-option label="领队证" value="领队证" />
            </el-select>
          </el-form-item>

          <el-form-item label="证书等级" prop="certificateLevel">
            <el-select
              v-model="form.certificateLevel"
              placeholder="请选择证书等级"
              class="!w-full"
            >
              <el-option label="初级" value="初级" />
              <el-option label="中级" value="中级" />
              <el-option label="高级" value="高级" />
              <el-option label="特级" value="特级" />
            </el-select>
          </el-form-item>

          <el-form-item label="有效期至" prop="expiryDate">
            <el-date-picker
              v-model="form.expiryDate"
              type="date"
              placeholder="选择有效期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="!w-full"
            />
          </el-form-item>
        </div>

        <el-form-item label="语言能力" prop="languages">
          <el-select
            v-model="form.languages"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择语言能力"
            class="!w-full"
          >
            <el-option label="中文" value="中文" />
            <el-option label="英语" value="英语" />
            <el-option label="粤语" value="粤语" />
            <el-option label="日语" value="日语" />
            <el-option label="韩语" value="韩语" />
            <el-option label="法语" value="法语" />
            <el-option label="德语" value="德语" />
            <el-option label="俄语" value="俄语" />
            <el-option label="西班牙语" value="西班牙语" />
          </el-select>
        </el-form-item>

        <el-form-item label="专长领域" prop="specialties">
          <el-select
            v-model="form.specialties"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择专长领域"
            class="!w-full"
          >
            <el-option label="历史文化" value="历史文化" />
            <el-option label="自然风光" value="自然风光" />
            <el-option label="美食文化" value="美食文化" />
            <el-option label="民俗风情" value="民俗风情" />
            <el-option label="摄影指导" value="摄影指导" />
            <el-option label="户外探险" value="户外探险" />
            <el-option label="购物推荐" value="购物推荐" />
            <el-option label="亲子体验" value="亲子体验" />
          </el-select>
        </el-form-item>

        <el-form-item label="证件照片" prop="certificateImages">
          <el-upload
            class="certificate-uploader"
            action="#"
            :http-request="uploadCertificate"
            list-type="picture-card"
            :file-list="certificateFileList"
            :on-remove="handleRemove"
            :before-upload="beforeCertificateUpload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="text-xs text-gray-500 mt-1">
            请上传清晰的证件照片，支持JPG、PNG格式，单个图片不超过5MB
          </div>
        </el-form-item>
      </div>

      <!-- 服务信息 -->
      <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm mb-6">
        <h3
          class="text-lg font-bold text-gray-900 dark:text-white mb-4 border-b border-gray-100 dark:border-gray-700 pb-2"
        >
          服务信息
        </h3>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <el-form-item label="服务费用" prop="price">
            <el-input-number
              v-model="form.price"
              :min="0"
              :precision="2"
              :step="10"
              class="!w-full"
            >
              <template #suffix>元/天</template>
            </el-input-number>
          </el-form-item>

          <el-form-item label="最大接待人数" prop="maxPeople">
            <el-input-number
              v-model="form.maxPeople"
              :min="1"
              :max="20"
              class="!w-full"
            >
              <template #suffix>人</template>
            </el-input-number>
          </el-form-item>
        </div>

        <el-form-item label="自我介绍" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            rows="5"
            placeholder="请输入自我介绍，包括服务亮点、专业背景等"
          />
        </el-form-item>
      </div>

      <!-- 路线信息 -->
      <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm mb-6">
        <div
          class="flex items-center justify-between mb-4 border-b border-gray-100 dark:border-gray-700 pb-2"
        >
          <h3 class="text-lg font-bold text-gray-900 dark:text-white">
            推荐路线
          </h3>
          <el-button type="primary" plain size="small" @click="addRoute"
            >添加路线</el-button
          >
        </div>

        <div
          v-for="(route, index) in form.routes"
          :key="index"
          class="mb-6 border border-gray-100 dark:border-gray-700 rounded-lg p-4"
        >
          <div class="flex justify-between items-center mb-4">
            <h4 class="font-bold">路线 {{ index + 1 }}</h4>
            <el-button
              type="danger"
              plain
              size="small"
              @click="removeRoute(index)"
              >删除</el-button
            >
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <el-form-item :label="'路线名称'" :prop="`routes.${index}.name`">
              <el-input v-model="route.name" placeholder="请输入路线名称" />
            </el-form-item>

            <el-form-item
              :label="'行程时长'"
              :prop="`routes.${index}.duration`"
            >
              <el-input v-model="route.duration" placeholder="例如: 8小时" />
            </el-form-item>
          </div>

          <el-form-item
            :label="'路线描述'"
            :prop="`routes.${index}.description`"
          >
            <el-input
              v-model="route.description"
              type="textarea"
              rows="2"
              placeholder="请输入路线描述"
            />
          </el-form-item>

          <el-form-item
            :label="'交通方式'"
            :prop="`routes.${index}.transportation`"
          >
            <el-select
              v-model="route.transportation"
              placeholder="请选择交通方式"
              class="!w-full"
            >
              <el-option label="步行" value="步行" />
              <el-option label="公交" value="公交" />
              <el-option label="步行+公交" value="步行+公交" />
              <el-option label="私家车" value="私家车" />
              <el-option label="包车" value="包车" />
            </el-select>
          </el-form-item>

          <div class="mt-4 border-t border-gray-100 dark:border-gray-700 pt-4">
            <div class="flex justify-between items-center mb-4">
              <h5 class="font-medium">景点安排</h5>
              <el-button
                type="primary"
                link
                size="small"
                @click="addSpot(index)"
                >添加景点</el-button
              >
            </div>

            <div
              v-for="(spot, spotIndex) in route.spots"
              :key="`${index}-${spotIndex}`"
              class="border border-gray-100 dark:border-gray-700 rounded p-3 mb-3"
            >
              <div class="flex justify-between items-center mb-2">
                <h6 class="text-sm font-medium">景点 {{ spotIndex + 1 }}</h6>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="removeSpot(index, spotIndex)"
                  >删除</el-button
                >
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                <el-form-item
                  :label="'景点名称'"
                  :prop="`routes.${index}.spots.${spotIndex}.name`"
                  label-width="80px"
                >
                  <el-input v-model="spot.name" placeholder="请输入景点名称" />
                </el-form-item>

                <el-form-item
                  :label="'游览时间'"
                  :prop="`routes.${index}.spots.${spotIndex}.time`"
                  label-width="80px"
                >
                  <el-input
                    v-model="spot.time"
                    placeholder="例如: 09:00-10:30"
                  />
                </el-form-item>
              </div>

              <el-form-item
                :label="'景点描述'"
                :prop="`routes.${index}.spots.${spotIndex}.description`"
                label-width="80px"
              >
                <el-input
                  v-model="spot.description"
                  type="textarea"
                  rows="2"
                  placeholder="请输入景点描述"
                />
              </el-form-item>
            </div>

            <div
              v-if="route.spots.length === 0"
              class="text-center text-gray-500 py-4"
            >
              暂无景点，点击"添加景点"按钮添加
            </div>
          </div>
        </div>

        <div
          v-if="form.routes.length === 0"
          class="text-center text-gray-500 py-8"
        >
          暂无路线，点击"添加路线"按钮添加
        </div>
      </div>

      <!-- 表单操作 -->
      <div class="flex justify-center space-x-4 mt-6">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Back, Plus } from "@element-plus/icons-vue";
import axios from '@/api/axios';

const route = useRoute();
const router = useRouter();
const formRef = ref(null);
const loading = ref(false);

// 是否为编辑模式
const isEdit = computed(() => route.params.id !== "new");
const guideId = computed(() => route.params.id);

// 表单数据
const form = reactive({
  name: "",
  phone: "",
  gender: "male",
  birthday: "",
  idNumber: "",
  location: [],
  experience: 0,
  status: "unverified",
  avatar: "",
  certificateNumber: "",
  issuingAuthority: "",
  certificateType: "",
  certificateLevel: "",
  expiryDate: "",
  languages: [],
  specialties: [],
  certificateImages: [],
  price: 0,
  maxPeople: 5,
  introduction: "",
  serviceAreas: [],
  serviceHours: {
    monday: { enabled: true, start: "09:00", end: "18:00" },
    tuesday: { enabled: true, start: "09:00", end: "18:00" },
    wednesday: { enabled: true, start: "09:00", end: "18:00" },
    thursday: { enabled: true, start: "09:00", end: "18:00" },
    friday: { enabled: true, start: "09:00", end: "18:00" },
    saturday: { enabled: true, start: "09:00", end: "18:00" },
    sunday: { enabled: true, start: "09:00", end: "18:00" },
  },
  bankName: "",
  bankAccount: "",
  bankAccountName: "",
});

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: "请输入导游姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  birthday: [{ required: true, message: "请选择出生日期", trigger: "change" }],
  idNumber: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号格式",
      trigger: "blur",
    },
  ],
  location: [
    { required: true, message: "请选择所在地区", trigger: "change" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  certificateType: [
    { required: true, message: "请选择证书类型", trigger: "change" },
  ],
  certificateLevel: [
    { required: true, message: "请选择证书等级", trigger: "change" },
  ],
  languages: [
    {
      required: true,
      type: "array",
      min: 1,
      message: "请至少选择一种语言能力",
      trigger: "change",
    },
  ],
  specialties: [
    {
      required: true,
      type: "array",
      min: 1,
      message: "请至少选择一个专长领域",
      trigger: "change",
    },
  ],
});

// 地区数据
const regionOptions = [
  {
    value: "广西",
    label: "广西",
    children: [
      {
        value: "贵港",
        label: "贵港",
        children: [
          { value: "港北区", label: "港北区" },
          { value: "港南区", label: "港南区" },
          { value: "覃塘区", label: "覃塘区" },
          { value: "平南县", label: "平南县" },
          { value: "桂平市", label: "桂平市" },
        ],
      },
      { value: "南宁", label: "南宁" },
      { value: "桂林", label: "桂林" },
      { value: "柳州", label: "柳州" },
      { value: "梧州", label: "梧州" },
      { value: "北海", label: "北海" },
    ],
  },
];

// 证件照片文件列表
const certificateFileList = ref([]);

// 获取导游详情
const getGuideDetail = async (id) => {
  loading.value = true;
  try {
    const response = await axios.get(`/admin/guides/${id}`);
    
    if (response && response.code === 200 && response.data) {
      const guideData = response.data;
      
      // 填充表单数据
      Object.keys(form).forEach(key => {
        if (guideData[key] !== undefined) {
          form[key] = guideData[key];
        }
      });
      
      // 处理证件照片
      if (guideData.certificateImages && guideData.certificateImages.length > 0) {
        certificateFileList.value = guideData.certificateImages.map((url, index) => ({
          name: `证件照片${index + 1}`,
          url
        }));
      }
    } else {
      ElMessage.warning("获取导游详情失败，使用默认数据");
      // 使用模拟数据作为备用
      mockGuideDetail();
    }
  } catch (error) {
    console.error("获取导游详情失败:", error);
    ElMessage.error("获取导游详情失败，使用默认数据");
    // 使用模拟数据作为备用
    mockGuideDetail();
  } finally {
    loading.value = false;
  }
};

// 模拟导游详情数据（备用）
const mockGuideDetail = () => {
  form.name = "李明";
  form.phone = "13800138000";
  form.gender = "male";
  form.birthday = "1990-01-15";
  form.idNumber = "450802199001150011";
  form.location = ["广西", "贵港", "港北区"];
  form.experience = 5;
  form.status = "verified";
  form.avatar = "/images/guides/guide1.jpg";
  form.certificateNumber = "GZ202301001";
  form.issuingAuthority = "国家旅游局";
  form.certificateType = "导游资格证";
  form.certificateLevel = "中级";
  form.expiryDate = "2028-06-15";
  form.languages = ["中文", "英语"];
  form.specialties = ["历史文化", "民俗风情"];
  form.certificateImages = [
    "/images/certificates/cert1.jpg",
    "/images/certificates/cert2.jpg",
  ];
  
  certificateFileList.value = [
    { name: "证件照片1", url: "/images/certificates/cert1.jpg" },
    { name: "证件照片2", url: "/images/certificates/cert2.jpg" },
  ];
  
  form.price = 380;
  form.maxPeople = 5;
  form.introduction = "资深导游，擅长讲解贵港历史文化，提供专业的导游服务。有多年带团经验，熟悉当地风土人情和历史典故。";
  form.serviceAreas = ["港北区", "港南区", "覃塘区"];
  form.bankName = "中国银行";
  form.bankAccount = "6222020200123456789";
  form.bankAccountName = "李明";
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    loading.value = true;
    
    // 构建提交数据
    const submitData = {...form};
    
    // 处理证件照片
    submitData.certificateImages = certificateFileList.value.map(file => file.url || file.response?.url);
    
    if (isEdit.value) {
      // 更新导游
      try {
        await axios.put(`/admin/guides/${guideId.value}`, submitData);
        ElMessage.success("导游信息更新成功");
        router.push("/admin/guides");
      } catch (error) {
        console.error("更新导游信息失败:", error);
        ElMessage.error("更新导游信息失败");
      }
    } else {
      // 创建导游
      try {
        await axios.post("/admin/guides", submitData);
        ElMessage.success("导游创建成功");
        router.push("/admin/guides");
      } catch (error) {
        console.error("创建导游失败:", error);
        ElMessage.error("创建导游失败");
      }
    }
  } catch (error) {
    console.error("表单验证失败:", error);
    ElMessage.error("请填写所有必填项");
  } finally {
    loading.value = false;
  }
};

// 头像上传前处理
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("头像图片只能是JPG或PNG格式!");
  }
  if (!isLt2M) {
    ElMessage.error("头像图片大小不能超过2MB!");
  }
  return isJPG && isLt2M;
};

// 上传头像
const uploadAvatar = async (params) => {
  try {
    // 创建FormData
    const formData = new FormData();
    formData.append('file', params.file);
    
    // 调用上传API
    const response = await axios.post('/admin/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (response && response.code === 200 && response.data) {
      form.avatar = response.data.url;
      ElMessage.success("头像上传成功");
    } else {
      // 使用模拟数据
      form.avatar = `/images/guides/guide${Math.floor(Math.random() * 3) + 1}.jpg`;
      ElMessage.warning("头像上传失败，使用测试图片");
    }
  } catch (error) {
    console.error("头像上传失败:", error);
    // 使用模拟数据
    form.avatar = `/images/guides/guide${Math.floor(Math.random() * 3) + 1}.jpg`;
    ElMessage.warning("头像上传失败，使用测试图片");
  }
};

// 证件照片上传前处理
const beforeCertificateUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPG) {
    ElMessage.error("证件照片只能是JPG或PNG格式!");
  }
  if (!isLt5M) {
    ElMessage.error("证件照片大小不能超过5MB!");
  }
  return isJPG && isLt5M;
};

// 上传证件照片
const uploadCertificate = async (params) => {
  try {
    // 创建FormData
    const formData = new FormData();
    formData.append('file', params.file);
    
    // 调用上传API
    const response = await axios.post('/admin/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (response && response.code === 200 && response.data) {
      params.onSuccess(response.data);
      ElMessage.success("证件照片上传成功");
    } else {
      // 使用模拟数据
      const mockedResponse = { 
        url: `/images/certificates/cert${Math.floor(Math.random() * 6) + 1}.jpg` 
      };
      params.onSuccess(mockedResponse);
      ElMessage.warning("证件照片上传失败，使用测试图片");
    }
  } catch (error) {
    console.error("证件照片上传失败:", error);
    // 使用模拟数据
    const mockedResponse = { 
      url: `/images/certificates/cert${Math.floor(Math.random() * 6) + 1}.jpg` 
    };
    params.onSuccess(mockedResponse);
    ElMessage.warning("证件照片上传失败，使用测试图片");
  }
};

// 移除证件照片
const handleRemove = (file) => {
  certificateFileList.value = certificateFileList.value.filter(
    (item) => item.uid !== file.uid
  );
};

// 返回
const goBack = () => {
  ElMessageBox.confirm("确定要离开当前页面吗？未保存的数据将会丢失。", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.push("/admin/guides");
    })
    .catch(() => {});
};

// 页面加载时获取数据
onMounted(() => {
  if (isEdit.value) {
    getGuideDetail(guideId.value);
  }
});
</script>

<style lang="scss" scoped>
.guide-edit-page {
  padding: 20px;

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .avatar-image {
      width: 120px;
      height: 120px;
      display: block;
      object-fit: cover;
    }
  }

  :deep(.el-form-item__label) {
    color: var(--el-text-color-regular);

    .dark & {
      color: var(--el-text-color-primary);
    }
  }
}
</style>
